package com.huilian.iotbox.data.service.impl;

import com.alibaba.fastjson.JSON;
import com.huilian.iotbox.data.dao.ErrorLogDao;
import com.huilian.iotbox.data.po.ErrorLog;
import com.huilian.iotbox.data.service.ErrorLogCommonService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author lizhiquan
 * @CreateDate: 2021-03-31-19-17
 * @Description:
 */
@Service
public class ErrorLogCommonServiceImpl implements ErrorLogCommonService {
    @Resource
    private ErrorLogDao errorLogDao;

    /**
     * @param errorName
     * @param entity
     * @param e
     */
    @Override
    public void writerInfoException(String errorName, Object entity, Exception e) {
        ErrorLog errorLog = new ErrorLog();
        errorLog.setDescription(errorName);
        errorLog.setErrorMsg(getExceptionAllInformation(e));
        errorLog.setDataJsonStr(entity == null ? errorName : JSON.toJSONString(entity));
        errorLogDao.insert(errorLog);
    }

    @Override
    public void writerInfoErrorLog(String errorName, Object entity) {
        ErrorLog errorLog = new ErrorLog();
        errorLog.setDescription(errorName);
        errorLog.setDataJsonStr(entity == null ? errorName : JSON.toJSONString(entity));
        errorLogDao.insert(errorLog);
    }

    @Override
    public Integer deleteByTime(String time) {
        return errorLogDao.deleteByTime(time);
    }


    private String getExceptionAllInformation(Exception e) {
        StackTraceElement stackTraceElement = e.getStackTrace()[0];
        String s1 = "File=" + stackTraceElement.getFileName();
        String s2 = ",Line=" + stackTraceElement.getLineNumber();
        String s3 = ",Method=" + stackTraceElement.getMethodName();
        StringBuilder sOut = new StringBuilder(s1).append(s2).append(s3).append("。异常：").append(e.getMessage()).append(":");
        StackTraceElement[] trace = e.getStackTrace();
        for (StackTraceElement s : trace) {
            sOut.append("\tat " + s + "\r\n");
        }
        return sOut.toString();
    }
}
